<?php

namespace ticket\modules\backend\models;

use Yii;

/**
 * This is the model class for table "tk_ticket_code".
 *
 * @property int $id
 * @property int $app_id
 * @property string $ticket_code
 * @property int $state
 * @property string $create_time 创建时间
 */
class TicketCode extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tk_ticket_code';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['app_id','required','message' => 'appId不能为空'],
            ['ticket_code','required','message' => '票码不能为空'],
            [['state','app_id'], 'integer'],
            [['create_time','title'], 'safe'],
            [['ticket_code'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'ticket_code' => 'Ticket Code',
            'state' => 'State',
            'title' => 'title',
            'create_time' => 'Create Time',
        ];
    }

    public function addInfo($app_id,$params)
    {
        $params['app_id'] = $app_id;
        $params['create_time'] = date("Y-m-d H:i:s");
        $model = new self();
        $model->setAttributes($params);
        if ($model->save()){
            return true;
        }
        return false;

    }


    public function modInfo($id,$params)
    {
        $model = self::find()->where(['id' => $id])->one();
        if (!is_null($model)){
            $model->setAttributes($params);
            if ($model->save()){
                return true;
            }
        }

        return false;
    }


    public function delInfo($appId,$id)
    {
        $model = self::find()->where(['id' => $id,'app_id' => $appId])->one();
        if (!is_null($model)){
            $model->state = 2;
            if ($model->save()){
                return true;
            }
        }

        return false;
    }


    public function getList($appId)
    {
        $model = self::find()->where(['app_id' => $appId,'state' => 1]);
        $data = $model->select(['id','ticket_code'])->asArray()->all();
        return $data;
    }


    public function list($appId,$params)
    {
        $page = isset($params['page'])?$params['page']:1;
        $limit = isset($params['size'])?$params['size']:10;
        $ticketCode = isset($params['ticketCode'])?$params['ticketCode']:'';

        $offset = ($page - 1) * $limit;
        $model = self::find();
        $model->where(['app_id' => $appId,'state' => 1]);
        $model->andFilterWhere(['like','ticket_code',$ticketCode]);

        $count = $model->count();
        $data = $model->select(['id','ticket_code','title','create_time'])->offset($offset)->limit($limit)->asArray()->all();
        $res['ticketCodeList'] = $data;
        $res['count'] = $count;
        $res['page'] = $page;
        $res['size'] = $limit;
        return $res;
    }

}
